package com.blockmeta.bbs.immodule.service;

import com.blankj.utilcode.util.LogUtils;

import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.dao.ChatMessage;
import com.blockmeta.bbs.immodule.dao.IMUserEntity;
import com.blockmeta.bbs.immodule.dao.Todo;
import com.blockmeta.bbs.immodule.utils.BroadcastHelper;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import buf.Msg;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;

@Sharable
public class ListMessageHandler extends SimpleChannelInboundHandler<List> {
    private Session session;

    public ListMessageHandler(Session session) {
        this.session = session;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, List messages) throws Exception {
        //
        if (messages != null && messages.size() > 0) {
            Object o = messages.get(0);
            // 聊天记录
            if (o instanceof Msg.ChatMessage) {
                onreciveChatMessageList(messages);
            }
            // 好友列表
            if (o instanceof Msg.Friends) {
                onReceiveFriendsList(messages);
            }
            // 代办列表
            if (o instanceof Msg.TodoMessage) {
                onReceiveTodoMessageList(messages);
            }

            // 群
            if (o instanceof Msg.ChatGroup) {
                onReceiveChatGroupMessageList(messages);
            }

        }

        ReferenceCountUtil.release(messages);
    }


    private void onreciveChatMessageList(List<Msg.ChatMessage> messages) {

        // 存储消息到本地
        if (messages != null && messages.size() > 0) {
            for (Msg.ChatMessage m : messages) {
                ChatMessage msg = new ChatMessage();
                msg.setChecked(false);
                msg.setWhoId(session.getUser().getUid());
                msg.setChatGroupId(m.getChatGroupId());
                String content = m.getContent();
                msg.setContent(content);

                msg.setDate((int) (System.currentTimeMillis() / 1000L));
                msg.setChatMessageId(m.getChatMessageId());
                // 获取的消息都是接收消息
                msg.setType(ChatMessage.TYPE_RECEIVE);
                msg.setMsgType(m.getMsgType());
                msg.setFromId(m.getFromId());
                msg.setToId(m.getToId());
                msg.setContentType(m.getContentType());
                msg.setFilePath(m.getFilePath());
                msg.setWhoId(session.getUser().getUid());
                msg.setUuid(m.getUuid());
                msg.setStatus(m.getStatus());
                // 如果是带附件的消息
                msg.setFileType(m.getFileType());
                msg.setFileName(m.getFileName());
                msg.setFileParam(m.getFileParam());
                IMApplicationContext.getChatMessageDomainService()
                        .addChatMessage(msg, session.getUser().getUid());
            }
        }
        // 广播事件
        BroadcastHelper.onReceiveChatMessageList(session);

    }

    /**
     * 获取好友列表，也需要保存到数据库！
     *
     * @param friends
     */
    private void onReceiveFriendsList(List<Msg.Friends> friends) {
        if (friends != null && friends.size() > 0) {


            List<IMUserEntity> groupListFriends = IMApplicationContext.getUserDomainService().getBookListFriends(session.getUser().getUid());
            Map<Long, IMUserEntity> groupMap = new HashMap<>(9);
            for (IMUserEntity groupEntity : groupListFriends) {
                groupMap.put(groupEntity.getUserId(), groupEntity);
            }
            for (Msg.Friends f : friends) {
                IMUserEntity _f = new IMUserEntity();
                _f.setAvatarPath(f.getAvatarPath());
                _f.setUserId(f.getUserId());
                _f.setType(Params.USER_PERSON);
                _f.setWhoId(session.getUser().getUid());
                _f.setName(f.getName().toString());
                _f.setRemarkName(f.getRemarkName().toString());
                _f.setFriend(true);
                _f.setSignature(f.getSignature());
                _f.setUserLevel(f.getGroupId());
                _f.setDate(f.getDate());
                IMApplicationContext.getUserDomainService().addAndUpdateUser(session.getUser().getUid(), _f);

                groupMap.remove(f.getId());
            }

            //在离线时的被删除好友需要同步
            if (groupMap.size() > 0) {
                for (Map.Entry<Long, IMUserEntity> entry : groupMap.entrySet()) {
                    LogUtils.i("author" + "Socket群组删除：" + entry.getValue().toString());
                    IMApplicationContext.getUserDomainService().deleteFriend(entry.getKey());
                }
            }
        }

        // 发出通知  广播事件
        BroadcastHelper.onReceiveFriendsList(session);

    }


    /**
     * 获取已加入群列表！
     *
     * @param chatGroup
     */
    private void onReceiveChatGroupMessageList(List<Msg.ChatGroup> chatGroup) {

        if (chatGroup != null && chatGroup.size() > 0) {

            List<IMUserEntity> groupListFriends = IMApplicationContext.getCircleDomainService().getGroupListFriends(session.getUser().getUid());
            Map<Long, IMUserEntity> groupMap = new HashMap<>(9);
            for (IMUserEntity groupEntity : groupListFriends) {
                groupMap.put(groupEntity.getUserId(), groupEntity);
            }
            for (Msg.ChatGroup c : chatGroup) {
//                LogUtils.i("author" +"离线ChatGroup："+new Gson().toJson(c));
                IMUserEntity entity = new IMUserEntity();
                entity.setAvatarPath(c.getGroupLogo());
                entity.setUserId(c.getId());
                entity.setType(Params.USER_GROUP);
                entity.setWhoId(session.getUser().getUid());
                entity.setName(c.getName());
                entity.setRemarkName("");
                entity.setFriend(false);
                entity.setSignature(c.getSlogan());
                entity.setGroupLevel(c.getGroupLevel());
                entity.setGroupCount(c.getGroupCount());
                entity.setNoDisturb(c.getNoDisturbing());
                entity.setIdentification(c.getIdentification());
                entity.setCircleClass(c.getType());
                entity.setCreateUserId(c.getCreateById());
                LogUtils.i("author" + "Socket群组：" + entity.toString());

                IMApplicationContext.getUserDomainService().addAndUpdateUser(session.getUser().getUid(), entity);
                groupMap.remove(c.getId());
            }

            //有可能服务器主动删除群,所以把服务端没返回的删除掉
            if (groupMap.size() > 0) {
                for (Map.Entry<Long, IMUserEntity> entry : groupMap.entrySet()) {
                    LogUtils.i("author" + "Socket群组删除：" + entry.getValue().toString());
                    IMApplicationContext.getCircleDomainService().deleteCircle(entry.getKey());
                }
            }
        }

//        // 发出通知  广播事件
        BroadcastHelper.onReceiveChatGroupList(session);
    }


    private void onReceiveTodoMessageList(List<Msg.TodoMessage> todoList) {
        LogUtils.i("author" + "获取到离线TODO");
        // 先将数据存入本地
        if (todoList != null && todoList.size() > 0) {
            for (Msg.TodoMessage m : todoList) {
                Todo todo = new Todo();
                todo.setCreateDate((int) (System.currentTimeMillis() / 1000L));
                todo.setChecked(false);
                todo.setAgree(false);
                todo.setComplete(false);
                todo.setRequestMsg(m.getRequestMsg().toString());
                todo.setTodoSubject(m.getTodoSubject().toString());
                //type 1==好友 2==群！
                todo.setType(m.getType());
                todo.setTodoId(m.getTodoId());
                todo.setFromId(m.getFromId());
                todo.setWhoId(session.getUser().getUid());
                todo.setGroupId(m.getGroupId());

                todo.setComplete(false);
                IMApplicationContext.getTodoDomainService()
                        .addTodo(todo);
                LogUtils.i("author" + "离线TODO：" + new Gson().toJson(todo));
            }
        }
        // TODO 测试强制发送消息然后发出通知
        BroadcastHelper.onReceiveTodoList(session);

    }


}